<template>
    <view class="container">
        <!-- 自定义顶部导航栏 -->
        <view class="custom-nav-bar nav-transparent">
            <view class="nav-left">
                <view class="back-button" @click="goBack">
                    <image src="../../static/home/right.png" class="back-icon" mode="widthFix" />
                </view>
                <image src="../../static/tab/logo.png" mode="widthFix" class="nav-bar-image logo-image" />
            </view>
            <view class="nav-right"></view>
        </view>
        <!-- <view class="bg-image-container">
      <image src="../../static/home/bg.png" mode="widthFix"
        class="nav-bar-image bg-image" />
    </view> -->
        <view class="search-header">
            <view class="search-container">
            <view @click="openSearchModal" class="search-input-box">
                <view class="search-input-content">
                    <!-- <image class="search-icon" src="../../static/searchCourt/Group.png"
                        mode="widthFix" /> -->
                    <view class="search-text-container" style="margin-left: 20rpx;">
                        <text class="search-selected-text" v-if="selectedDate || selectedTimeSlots.length > 0">
                            {{ selectedDate || '今日' }}
                            <text v-if="selectedTimeSlots.length > 0" class="search-time-slots">
                                {{ selectedTimeSlots.length > 1 ? `${selectedTimeSlots[0]} 等${selectedTimeSlots.length}个时段` : selectedTimeSlots[0] }}
                            </text>
                        </text>
                        <text class="search-placeholder" v-else>搜索场地</text>
                    </view>
                </view>
                
            </view>
        </view>
        <view @click="performSearch" class="search-button" :class="{ 'loading': loading }">
            <image v-if="loading" class="loading-icon" src="../../static/home/loading.png" mode="widthFix"></image>
            <text v-if="!loading">查询</text>
            <text v-else>搜索中...</text>
        </view>
        <view style="width: 80rpx;height: 80rpx;margin-top: 200rpx;margin-left: 10rpx;margin-right: 10rpx;">
            <!-- 地图/列表切换按钮 -->
            <view class="map-toggle-container" @click="toggleMapView">
                <image 
                    :src="isMapExpanded ? '/static/searchCourt/list.png' : '/static/searchCourt/map.png'"
                    class="map-toggle-icon"
                    mode="aspectFit"
                ></image>
            </view>
        </view>
        </view>
        
        <view>
            <view v-if="!isVenueListExpanded" class="all-icon" @click="toggleVenueListExpansion">
                    <image src="../../static/home/right.png" class="expand-arrow" :class="{ expanded: isVenueListExpanded }" mode="widthFix" />
                   </view>
            <scroll-view 
                v-if="!isVenueListExpanded"
                scroll-x 
                class="scroll-view-container" 
                ref="venueScrollView"
            >
                <view style="display: flex;width: fit-content;">
                    <view 
                        class="court-type"
                        :class="{ active: activeVenueFilter === 'all' }"
                        @click="filterByVenue('all')"
                    >
                        全部
                    </view>
                    <!-- 加载状态时显示loading图标 -->
                    <view v-if="loading" class="court-type loading-venue">
                        <image class="loading-icon-small" src="../../static/home/loading.png" mode="widthFix"></image>
                        <text>加载中...</text>
                    </view>
                    <!-- 非加载状态时显示球馆列表 -->
                    <view 
                        v-if="!loading"
                        v-for="(venue, index) in uniqueVenues" 
                        :key="index"
                        class="court-type"
                        :class="{ active: activeVenueFilter === venue }"
                        @click="filterByVenue(venue)"
                    >
                        {{ getVenueDisplayName(venue) }}
                    </view>
                   
                </view>
            </scroll-view>
            
            <!-- 展开状态的球馆列表 -->
            <view class="expanded-venue-container" :class="{ show: isVenueListExpanded }">
                <view class="expanded-venue-header">
                    <text class="expanded-title">选择球馆</text>
                    <view class="all-icon" @click="toggleVenueListExpansion">
                        <image src="../../static/home/right.png" style="width: 36rpx; height: 36rpx;transform: rotate(270deg);" mode="widthFix" />
                    </view>
                </view>
                <view class="expanded-venue-grid">
                    <view 
                        class="expanded-court-type"
                        :class="{ active: activeVenueFilter === 'all' }"
                        @click="filterByVenue('all')"
                    >
                        全部
                    </view>
                    <view 
                        v-for="(venue, index) in uniqueVenues" 
                        :key="index"
                        class="expanded-court-type"
                        :class="{ active: activeVenueFilter === venue }"
                        @click="filterByVenue(venue)"
                    >
                        {{ getVenueDisplayName(venue) }}
                    </view>
                </view>
            </view>
        </view>
        <!-- 地图展示 -->
        <view class="map-section" :class="{ 'map-expanded': isMapExpanded, 'map-collapsed': !isMapExpanded }">
            <map 
                class="search-map-container"
                :class="{ 'map-expanded': isMapExpanded, 'map-collapsed': !isMapExpanded }"
                :latitude="mapLatitude"
                :longitude="mapLongitude"
                :scale="mapScale"
                :markers="mapMarkers"
                :show-location="true"
                :enable-traffic="false"
                :enable-compass="false"
                :enable-3D="false"
                marker-class="marker-transition"
                @labeltap="onMarkerTap"
            ></map>
        </view>
        <!-- 搜索结果展示 -->
        <view class="content">
            <VenueListNew 
                ref="venueListNew"
                :venues="venueList" 
                :loading="loading"
                :hasMore="hasMore"
                :selectedDate="selectedDate"
                :selectedTimeSlots="selectedTimeSlots"
                :selectedCourtType="selectedCourtType"
                :showStandardCourtsOnly="showStandardCourtsOnly"
                :isVenueListExpanded="isVenueListExpanded"
                @venue-click="goToVenueDetail"
                @load-more="loadMoreVenues"
                @update:venues="updateVenues"

            />
        </view>

        <!-- 搜索模态框 -->
        <view class="modal-overlay" v-if="showModal" @click="closeSearchModal"></view>
        <view class="search-modal" :class="{ 'modal-show': showModal }">
            <view class="modal-header">
                <view class="header-left">
                    <text class="modal-title">筛选</text>
                    <view class="filter-toggle" style="margin-left: 30rpx;"> 
                        
                        <view class="custom-switch " style="margin-right: 20rpx;" :class="{ 'active': showStandardCourtsOnly }" @click="toggleStandardSwitch">
                            <view class="switch-thumb"></view>
                        </view>
                        <view class="filter-label" style="margin-bottom: 0 !important;color: #999;">只显示标准场</view>
                    </view>
                </view>
                <view class="header-right">
                    
                    <text class="modal-cancel" @click="closeSearchModal">取消</text>
                </view>
            </view>

            <view class="search-filters">
                <view class="filter-item">
                    <view class="filter-label">选择日期</view>
                    <view class="week-selector-container">
                        <scroll-view scroll-x class="week-scroll-view">
                            <view class="week-days-container">
                                <view 
                                    v-for="(day, index) in weekDays" 
                                    :key="index"
                                    class="week-day-item"
                                    :class="{ 
                                        'active': selectedDate === day.dateString,
                                        'today': day.isToday 
                                    }"
                                    @click="selectWeekDay(day)"
                                >
                                    <view class="week-day-name">{{ day.weekName }}</view>
                                    <view class="week-day-date">{{ day.monthDay }}</view>
                                </view>
                            </view>
                        </scroll-view>
                    </view>
                </view>
                <view class="filter-item">
                    <view class="filter-label">时间</view>
                    <view
                        style="width: 690rpx; margin: 0rpx auto;margin-bottom: 20rpx;display: flex;flex-direction: column;justify-content: start;align-items: center;">
                        <view @click="showTimePicker"
                            style="font-size: 26rpx; display: flex;justify-content: space-between;align-items: center; width: 694rpx; height: 80rpx;background: #F7F7F7;border-radius: 24rpx;display: flex;">
                            <view style="display: flex;align-items: center; padding-left: 30rpx;">
                                <view class="time-tags-container">
                                    <view 
                                        v-for="(time, index) in selectedTimeSlots" 
                                        :key="index"
                                        class="time-selected-tag"
                                    >
                                        <text class="time-tag-text">{{ time }}</text>
                                        <text class="time-tag-remove" @click.stop="removeTimeSlot(index)">×</text>
                                    </view>
                                    <text v-if="selectedTimeSlots.length === 0" style="color: #999;">选择时间</text>
                                </view>
                            </view>
                            <image
                                style="width: 36rpx;height: 36rpx;margin: 0 30rpx;transform: rotate(90deg);opacity: 0.5;"
                                src="../../static/home/right.png" mode="widthFix" />
                        </view>
                    </view>
                </view>
                <view class="filter-item">
                    <view class="filter-label">选择球馆</view>
                    <view
                        style="width: 690rpx; margin: 0rpx auto;margin-bottom: 20rpx;display: flex;flex-direction: column;justify-content: start;align-items: center;">
                        <ClubSelectorPopup 
                        ref="clubSelectorPopup"
                            :options="clubOptions" 
                            v-model="selectedClubs" 
                            @change="toggleClubFilter" 
                            @court-type-change="toggleCourtTypeFilter"
                            @district-filter="handleDistrictFilter"
                            @confirm="performSearch" 
                        />
                    </view>
                </view>
            </view>
            <view class="modal-actions">
                <view class="reset-btn" @click="resetFilters">重置</view>
                <view class="search-btn" :class="{ 'loading': loading }" @click="performSearch">
                    <image v-if="loading" class="loading-icon" src="../../static/home/loading.png" mode="widthFix"></image>
                    <text>{{ loading ? '搜索中...' : '查询' }}</text>
                </view>
            </view>
        </view>
        

        <!-- 时间选择底部弹窗 -->
        <view class="bottom-modal-mask" :class="{ show: showTimeModal }" @click="closeTimeModal">
            <view class="bottom-modal" :class="{ show: showTimeModal }" @click.stop>
                <view class="bottom-modal-header">
                    <text class="modal-title">选择时间范围</text>
                    <text class="modal-cancel" @click="closeTimeModal">取消</text>
                </view>
                <view class="bottom-modal-content">
                    <view class="time-tags-grid">
                        <view 
                            v-for="(time, index) in timeSlots" 
                            :key="index"
                            class="time-tag-popup"
                            :class="{ 
                                active: selectedTimeSlots.includes(time.value),
                                'golden-time': time.value === '18:00-19:00' || time.value === '19:00-20:00' || time.value === '20:00-21:00' || time.value === '21:00-22:00',
                                disabled: isTimeSlotDisabled(time.value)
                            }"
                            @click="toggleTimeSlotInModal(time.value)"
                        >
                            <text class="time-label-popup">{{ time.label }}</text>
                        </view>
                    </view>
                </view>
                <view class="bottom-modal-footer">
                    <view class="modal-buttons">
                        <view class="modal-reset-button" @click="resetTimeSlotsInModal">重置</view>
                        <button class="confirm-button" @click="confirmTimeSelection">确定</button>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import VenueListNew from '@/components/VenueListNew.vue';
import ClubSelectorPopup from '@/components/ClubSelectorPopup.vue';
import { getVenueList } from '@/common/request.js';
import { getVenueByName, getVenueAllAddresses } from '@/common/venueConfig.js';
import venueConfig from '@/common/venueConfig.json';
import smallVenueConfig from '@/common/smallVenueConfig.json';
import { Venue } from '@/common/models.js';
import { getCurrentCity } from '@/common/cityUtils.js';
import { XiangYang33XiaoZhenProcessor } from '@/common/venueProcessors/XiangYang33XiaoZhenProcessor.js';
import courtTypeConfig from '@/components/courtTypeConfig.json';
import { BaseVenueProcessor } from '@/common/venueProcessors/BaseVenueProcessor.js'
import { YueJiChengShiZhiGuangProcessor } from '@/common/venueProcessors/YueJiChengShiZhiGuangProcessor.js'
import { YueJiFengTaiProcessor } from '@/common/venueProcessors/YueJiFengTaiProcessor.js'
import { YueJiDianShangYuanProcessor } from '@/common/venueProcessors/YueJiDianShangYuanProcessor.js'
import { YueJiHuMenDaDaoProcessor } from '@/common/venueProcessors/YueJiHuMenDaDaoProcessor.js'
import { XiangYangXingHeChengProcessor } from '@/common/venueProcessors/XiangYangXingHeChengProcessor.js'
import { XiangYangZhenXingChengProcessor } from '@/common/venueProcessors/XiangYangZhenXingChengProcessor.js'
import { AiDongJinFengProcessor } from '@/common/venueProcessors/AiDongJinFengProcessor.js'
import { AiLiProcessor } from '@/common/venueProcessors/AiLiProcessor.js'
import { BuJiProcessor } from '@/common/venueProcessors/BuJiProcessor.js'
import { DongChengProcessor } from '@/common/venueProcessors/DongChengProcessor.js'
import { DongGuanTiYuZhongXinProcessor } from '@/common/venueProcessors/DongGuanTiYuZhongXinProcessor.js'
import { LuoJieProcessor } from '@/common/venueProcessors/LuoJieProcessor.js'
import { ShengXuanZhiXingProcessor } from '@/common/venueProcessors/ShengXuanZhiXingProcessor.js'
import { ShengXuanDaZhuangProcessor } from '@/common/venueProcessors/ShengXuanDaZhuangProcessor.js'
import { SongShanHuTaiLuGeProcessor } from '@/common/venueProcessors/SongShanHuTaiLuGeProcessor.js'
import { ThreePointFiveFuDiProcessor } from '@/common/venueProcessors/ThreePointFiveFuDiProcessor.js'

import { TuoDeProcessor } from '@/common/venueProcessors/TuoDeProcessor.js'
import { WeiAoXiangShuProcessor } from '@/common/venueProcessors/WeiAoXiangShuProcessor.js'
import { XiangYangCaiHongWanProcessor } from '@/common/venueProcessors/XiangYangCaiHongWanProcessor.js'
import { XiangYangKangDiProcessor } from '@/common/venueProcessors/XiangYangKangDiProcessor.js'
import { XiangYangYaYuanProcessor } from '@/common/venueProcessors/XiangYangYaYuanProcessor.js'
import { YuanFengProcessor } from '@/common/venueProcessors/YuanFengProcessor.js'
import { ZhuoLeProcessor } from '@/common/venueProcessors/ZhuoLeProcessor.js'
import { ZhuoLeTennisProcessor } from '@/common/venueProcessors/ZhuoLeTennisProcessor.js'
import { UPTennisSanXiSKYProcessor } from '@/common/venueProcessors/UPTennisSanXiSKYProcessor.js'
import { KuaiKeProcessor } from '@/common/venueProcessors/KuaiKeProcessor.js'
import { JinManGuanProcessor } from '@/common/venueProcessors/JinManGuanProcessor.js'
import { JinManGuanWeiSiTingProcessor } from '@/common/venueProcessors/JinManGuanWeiSiTingProcessor.js'
import { JinManGuanHuangGuanProcessor } from '@/common/venueProcessors/JinManGuanHuangGuanProcessor.js'
import { JinManGuanHaiZhuProcessor } from '@/common/venueProcessors/JinManGuanHaiZhuProcessor.js'
import { JinManGuanHuaGongBeiProcessor } from '@/common/venueProcessors/JinManGuanHuaGongBeiProcessor.js'
import { JinManGuanHuaGongXiProcessor } from '@/common/venueProcessors/JinManGuanHuaGongXiProcessor.js'
import { JinManGuanPanJiangHuaYuanProcessor } from '@/common/venueProcessors/JinManGuanPanJiangHuaYuanProcessor.js'
import { JinManGuanTianHeChengProcessor } from '@/common/venueProcessors/JinManGuanTianHeChengProcessor.js'
import { JinManGuanHuaGongDaXueChengProcessor } from '@/common/venueProcessors/JinManGuanHuaGongDaXueChengProcessor.js'
import { JinManGuanBaiYunProcessor } from '@/common/venueProcessors/JinManGuanBaiYunProcessor.js'
import { JinManGuanZhuJiangXinChengProcessor } from '@/common/venueProcessors/JinManGuanZhuJiangXinChengProcessor.js'
import { JinManGuanPaZhouProcessor } from '@/common/venueProcessors/JinManGuanPaZhouProcessor.js'
import { JinManGuanHuaMeiLuHuProcessor } from '@/common/venueProcessors/JinManGuanHuaMeiLuHuProcessor.js'
import { JinManGuanHuaMeiXueXiaoProcessor } from '@/common/venueProcessors/JinManGuanHuaMeiXueXiaoProcessor.js'
import { JinManGuanQiFengShanProcessor } from '@/common/venueProcessors/JinManGuanQiFengShanProcessor.js'
import { HuaGuoShanProcessor } from '@/common/venueProcessors/HuaGuoShanProcessor.js'
import { TwoZeroNineTennisProcessor } from '@/common/venueProcessors/TwoZeroNineTennisProcessor.js'
import { JinLinShanZhuangProcessor } from '@/common/venueProcessors/JinLinShanZhuangProcessor.js'
import { YuFengWeiJiangBianProcessor } from '@/common/venueProcessors/YuFengWeiJiangBianProcessor.js'
import { FengTaiHuaYuanProcessor } from '@/common/venueProcessors/FengTaiHuaYuanProcessor.js'
import { TuoPuNanGuoHuaYuanProcessor } from '@/common/venueProcessors/TuoPuNanGuoHuaYuanProcessor.js'
import { TuoPuWanShengWeiProcessor } from '@/common/venueProcessors/TuoPuWanShengWeiProcessor.js'
import { TuoPuXinGangDongProcessor } from '@/common/venueProcessors/TuoPuXinGangDongProcessor.js'
import { TuoPuBaiYunHuJinBoTianDiProcessor } from '@/common/venueProcessors/TuoPuBaiYunHuJinBoTianDiProcessor.js'
import { JianChaoTennisProcessor } from '@/common/venueProcessors/JianChaoTennisProcessor.js'
import { QingYunTennisProcessor } from '@/common/venueProcessors/QingYunTennisProcessor.js'
import { QuanAiLiWanProcessor } from '@/common/venueProcessors/QuanAiLiWanProcessor.js'
import { YunBaoLuoLunSiProcessor } from '@/common/venueProcessors/YunBaoLuoLunSiProcessor.js'
import { HanWeiTennisProcessor } from '@/common/venueProcessors/HanWeiTennisProcessor.js'
import { MteamJiaHeGuangFengProcessor } from '@/common/venueProcessors/MteamJiaHeGuangFengProcessor.js'
import { MteamHuangPuProcessor } from '@/common/venueProcessors/MteamHuangPuProcessor.js'

export default {
    components: {
        VenueListNew,
        ClubSelectorPopup
    },
    data() {
        return {
            showModal: false,
            searchKeyword: '',
            selectedDate: this.getCurrentDate(),
            selectedTimeSlots: [],
            timeSlots: this.generateTimeSlots(),
            venueList: [],
            loading: false,
            hasMore: true,
            page: 1,
            pageSize: 10,
            currentCity: null, // 当前城市信息
            clubOptions: [
                '所有球馆',
                '库卡网球',
                '向阳彩鸿湾',
                '向阳康帝校区',
                '向阳雅园校区',
                '向阳33小镇校区',
                '向阳星河城校区',
                '向阳振兴城校区',
                '拓德网球俱乐部',
                '爱动金丰网球俱乐部',
                '卓乐网球',
                '爱力网球',
                '东城体育公园',
                '东莞市体育中心',
                '3.5+网球（金色华庭店）',
                '3.5+网球（福地）',
                '松山湖太鲁阁公园',
                '为傲网球（香树店）',
                '埗击网球',
                '源峰网球',
                '罗杰网球',
                '月击网球（城市之光校区）',
                '月击网球（丰泰校区）',
                '月击网球（电商园校区）',
                '月击网球（虎门大道校区）',
                '晟旋网球(执信店)',
                '晟旋网球(大壮国际店)',
                'UPTennis三溪SKY店',
                '快客网球',
                '金满贯(中国大酒店)',
                '金满贯(皇冠假日)',
                '金满贯(海珠香格里拉)',
                '金满贯(华工北)',
                '金满贯(华工西)',
                '金满贯(畔江花园)',
                '金满贯(天河城喜来登)',
                '金满贯(华工大学城)',
                '金满贯(威斯汀)',
                '金满贯(白云)',
                '金满贯(珠江新城)',
                '金满贯(琶洲保利世贸)',
                '金满贯(华美麓湖)',
                '金满贯(华美学校)',
                '金满贯(旗峰山)',
                '花果山网球馆',
                '209网球中心',
                '锦林山庄网球馆',
                '裕丰围江边网球场',
                '丰泰花园网球场',
                '拓普网球(南国花园)',
                '拓普网球(万胜围)',
                '拓普网球(新港东)',
                '拓普网球(白云湖金铂天地)',
                '健潮网球',
                '青芸网球',
                '全爱网球(荔湾店)',
                '云堡罗伦斯网球',
                '瀚为网球',
                'Mteam网球(嘉禾广丰)',
                'Mteam网球(黄埔)'
            ],
            selectedClubs: [0], // 默认选中所有球馆（索引0）
            selectedClubNames: [],
            courtTypeOptions: ['不限', '硬地室外场', '硬地风雨场/室内场', '红土风雨场'],
            selectedCourtType: '不限',
            courtTypeConfig: courtTypeConfig,
            // 时间选择弹窗相关数据
            showTimeModal: false,
            // 备份时间选择，用于取消时恢复
            backupTimeSlots: [],
            // 日期选择弹窗相关数据

            // 地区筛选后的球馆名称
            districtFilteredVenues: [],
            // 球馆导航相关
            uniqueVenues: [], // 去重后的球馆列表
            activeVenueFilter: 'all', // 当前激活的球馆过滤器，'all'表示全部
            allVenueList: [], // 保存所有场地数据，用于过滤
            // 标准场过滤
            showStandardCourtsOnly: true,
            // 球馆列表展开状态
            isVenueListExpanded: false,
            // 地图展开状态
            isMapExpanded: false, // 默认收缩状态
            // 地图相关数据
            mapLatitude: Number(23.02067), // 默认纬度（向阳彩鸿湾）
            mapLongitude: Number(113.75179), // 默认经度（向阳彩鸿湾）
            mapScale: 12, // 地图缩放级别
            mapMarkers: [], // 地图标记点
            selectedMarkerId: null, // 当前选中的标记点ID
            uniqueVenuesOrigin:[],
            // 星期选择相关数据
            weekDays: [] // 接下来一周的日期数据

        }
    },
    methods: {
        getCurrentDate() {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        
        // 生成接下来一周的日期数据
        generateWeekDays() {
            const weekDays = [];
            const today = new Date();
            const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            
            for (let i = 0; i < 7; i++) {
                const date = new Date(today);
                date.setDate(today.getDate() + i);
                
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const dateString = `${year}-${month}-${day}`;
                
                weekDays.push({
                    dateString: dateString,
                    weekName: i === 0 ? '今天' : weekNames[date.getDay()],
                    monthDay: `${month}/${day}`,
                    isToday: i === 0
                });
            }
            
            return weekDays;
        },
        
        // 选择星期日期
        selectWeekDay(day) {
            this.selectedDate = day.dateString;
        },
        
        // 球馆导航相关方法
        getVenueDisplayName(venue) {
            // 从venueConfig.json获取球馆的正确名称
            const venueInfo = getVenueByName(venue);
            if (venueInfo && venueInfo.name) {
                // 获取球馆显示名称，去掉常见后缀以简化显示
                return venueInfo.name.replace(/网球|俱乐部|校区|公园|中心|网球馆|网球场/g, '');
            }
            
            // 如果在配置中找不到，则去掉后缀返回
            return venue.replace(/网球|俱乐部|校区|公园|中心|网球馆|网球场/g, '');
        },
        
        updateUniqueVenues() {
             // 从所有场地列表中提取唯一的球馆名称，确保导航标签不会因过滤而变化
             const venueNames = new Set();
             const venueDistanceMap = new Map(); // 存储每个球馆的最近距离
             
             // 首先从allVenueList收集所有球馆名称
             this.allVenueList.forEach(venue => {
                 if (venue.dataSource) {
                     venueNames.add(venue.dataSource);
                 }
             });
             
             // 从已排序的venueList中获取距离信息
             this.venueList.forEach(venue => {
                 if (venue.dataSource && venue.distance !== undefined) {
                     const currentDistance = parseFloat(venue.distance);
                     if (!venueDistanceMap.has(venue.dataSource) || 
                         currentDistance < venueDistanceMap.get(venue.dataSource)) {
                         venueDistanceMap.set(venue.dataSource, currentDistance);
                     }
                 }
             });
             
             // 按距离排序球馆名称
             const sortedVenues = Array.from(venueNames).sort((a, b) => {
                 const distanceA = venueDistanceMap.get(a) || Infinity;
                 const distanceB = venueDistanceMap.get(b) || Infinity;
                 return distanceA - distanceB;
             });
             
             this.uniqueVenues = sortedVenues;
         },
         
         generateTimeSlots() {
            const slots = [];
            for (let hour = 6; hour <= 23; hour++) {
                const startHour = hour.toString().padStart(2, '0');
                const endHour = (hour + 1).toString().padStart(2, '0');
                slots.push({
                    label: `${startHour}:00-${endHour}:00`,
                    value: `${startHour}:00-${endHour}:00`
                });
            }
            return slots;
        },
        
        openSearchModal() {
            this.showModal = true
        },
        closeSearchModal() {
            this.showModal = false
            this.$refs.clubSelectorPopup.cancelSelection()
        },
        clearSearch() {
            this.searchKeyword = ''
        },
        resetFilters() {
            this.searchKeyword = ''
            this.selectedDate = this.getCurrentDate()
            this.selectedTimeSlots = []
            this.selectedClubs = [0]
            this.selectedClubNames = []
            this.selectedCourtType = '不限'
            this.districtFilteredVenues = []
            this.showStandardCourtsOnly = true
            this.venueList = []
            this.page = 1
            
            // 重置 ClubSelectorPopup 组件的选择状态
            if (this.$refs.clubSelectorPopup) {
                this.$refs.clubSelectorPopup.resetSelection()
            }
        },
        async performSearch() {
            if (this.loading) return; // 防止重复点击
            
            console.log('执行搜索:', {
                keyword: this.searchKeyword,
                date: this.selectedDate,
                timeSlots: this.selectedTimeSlots,
                clubs: this.selectedClubNames,
                courtType: this.selectedCourtType
            })
            
            this.loading = true;
            
            try {
                // 执行搜索逻辑
                await this.searchVenues();
                this.closeSearchModal();
            } catch (error) {
                console.error('搜索失败:', error);
                uni.showToast({
                    title: '搜索失败，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        

        // 时间选择相关方法
        showTimePicker() {
            // 备份当前选择的时间槽
            this.backupTimeSlots = [...this.selectedTimeSlots];
            // 显示时间选择弹窗
            this.showTimeModal = true;
        },
        
        closeTimeModal() {
            // 恢复备份的时间选择
            this.selectedTimeSlots = [...this.backupTimeSlots];
            // 关闭弹窗
            this.showTimeModal = false;
        },
        
        toggleTimeSlotInModal(timeSlot) {
            const index = this.selectedTimeSlots.indexOf(timeSlot);
            if (index > -1) {
                // 如果已选中，则移除
                this.selectedTimeSlots.splice(index, 1);
            } else {
                // 如果未选中，则添加
                this.selectedTimeSlots.push(timeSlot);
            }
        },
        
        resetTimeSlotsInModal() {
            this.selectedTimeSlots = [];
        },
        
        confirmTimeSelection() {
            // 确认时间选择
            // 重置页面
            this.page = 1;
            this.venueList = [];
            // 关闭弹窗
            this.showTimeModal = false;
        },
        
        removeTimeSlot(index) {
            this.selectedTimeSlots.splice(index, 1);
        },
        
        isTimeSlotDisabled(timeSlot) {
            // 检查是否为当天日期
            const today = new Date();
            const selectedDate = new Date(this.selectedDate);
            const isToday = today.toDateString() === selectedDate.toDateString();
            
            if (isToday) {
                // 获取当前小时
                const currentHour = today.getHours();
                // 解析时间槽的开始小时
                const [startHour] = timeSlot.split('-')[0].split(':');
                return parseInt(startHour) < currentHour;
            }
            
            return false;
        },
        
        // 球馆筛选相关方法
        toggleClubFilter(e) {
            // 处理多选俱乐部过滤
            const selectedIndices = e.detail.value;
            
            // 更新选中的俱乐部索引
            this.selectedClubs = selectedIndices;
            
            // 更新选中的俱乐部名称
            if (selectedIndices.length === 0 || (selectedIndices.length === 1 && selectedIndices[0] === 0)) {
                // 如果没有选择或选择的是"所有球馆"，则清空选中的俱乐部名称
                this.selectedClubNames = [];
                
                // 如果有地区筛选后的球馆名称，则使用这些球馆名称
                if (this.districtFilteredVenues.length > 0) {
                    this.selectedClubNames = this.districtFilteredVenues;
                }
            } else {
                // 过滤掉"所有球馆"选项（索引为0）
                const filteredIndices = selectedIndices.filter(index => index !== 0);
                // 更新为当前选中的俱乐部
                this.selectedClubNames = filteredIndices.map(index => this.clubOptions[index]);
            }
            
            // 重置页面
            this.page = 1;
            this.venueList = [];
        },
        
        toggleCourtTypeFilter(e) {
            // 更新选中的球场类型
            this.selectedCourtType = e.detail.courtType;
            // 重置页面
            this.page = 1;
            this.venueList = [];
        },
        
        handleDistrictFilter(e) {
            // 处理地区筛选事件
            const { venueNames, province, city, district } = e.detail;
            
            // 保存地区筛选后的球馆名称
            this.districtFilteredVenues = venueNames;
            
            // 如果当前选择的是"所有球馆"且有地区筛选，则更新选中的俱乐部名称
            if (this.selectedClubs.length === 1 && this.selectedClubs[0] === 0) {
                this.selectedClubNames = venueNames;
            }
            
            // 重置页面
            this.page = 1;
            this.venueList = [];
        },
        
        handleStandardCourtFilter(e) {
            // 处理标准场过滤事件
            const { showStandardCourtsOnly } = e.detail;
            
            // 更新标准场过滤状态
            this.showStandardCourtsOnly = showStandardCourtsOnly;
            
            // 重置页面
            this.page = 1;
            this.venueList = [];
        },
        
        toggleStandardSwitch() {
            this.showStandardCourtsOnly = !this.showStandardCourtsOnly;
            // 重置页面
            this.page = 1;
            this.venueList = [];
        },
        
        toggleVenueListExpansion() {
            this.isVenueListExpanded = !this.isVenueListExpanded;
        },
        
        // 切换地图展开/收缩状态
        toggleMapView() {
            this.isMapExpanded = !this.isMapExpanded;
        },
        
        goBack() {
            uni.navigateBack({
                delta: 1
            });
        },
        
        // 搜索相关方法
        searchVenues() {
            // 重置页面
            this.page = 1;
            // 加载场地数据
            return this.loadVenueData();
        },
        
        async loadVenueData() {
            // 移除这里的loading检查，因为performSearch已经处理了loading状态
            // if (this.loading) return;
            
            // 不在这里设置loading，由调用方控制
            // this.loading = true;
            // 清空当前场地列表
            this.venueList = [];
            this.allVenueList = [];
            
            try {
                // 获取当前城市信息
                const currentCity = getCurrentCity();
                
                // 根据选中的俱乐部决定请求哪些数据
                // 如果有地区筛选后的球馆名称，则使用这些球馆名称
                let selectedClubs = this.selectedClubNames.length > 0 ? 
                    this.selectedClubNames : 
                    (this.districtFilteredVenues.length > 0 ? this.districtFilteredVenues : ['所有球馆']);
                
                // 记录是否原本选择了"所有球馆"
                const isAllVenuesSelected = selectedClubs.includes('所有球馆');
                
                // 如果选择的是"所有球馆"，根据当前城市过滤并按距离排序
                if (isAllVenuesSelected) {
                    if (currentCity && currentCity.name) {
                        // 根据venueConfig.json中的城市信息过滤球馆
                        const cityVenues = venueConfig.venues.filter(venue => {
                            return venue.addresses && venue.addresses.some(address => 
                                address.city === currentCity.name
                            );
                        }).map(venue => venue.name);
                        
                        // 只选择当前城市的球馆，并且这些球馆在clubOptions中存在
                        const availableVenues = this.clubOptions.filter(club => 
                            club !== '所有球馆' && cityVenues.includes(club)
                        );
                        
                        // 按距离排序球馆
                        const sortedVenues = this.sortVenuesByDistance(availableVenues);
                        selectedClubs = sortedVenues.map(venue => venue.name);
                        
                        console.log(`根据城市${currentCity.name}过滤并按距离排序后的球馆:`, selectedClubs);
                    }
                } else {
                    // 如果不是"所有球馆"，也按距离排序选中的球馆
                    const sortedVenues = this.sortVenuesByDistance(selectedClubs);
                    selectedClubs = sortedVenues.map(venue => venue.name);
                    console.log('按距离排序后的选中球馆:', selectedClubs);
                }
                
                // 重置过滤器为全部
                this.activeVenueFilter = 'all';
                
                // 创建所有异步任务数组
                const venuePromises = [];
                
                // 创建球馆处理器映射
                const venueProcessorMap = {
                    '库卡网球': {
                        processor: ZhuoLeProcessor,
                        getDataMethod: async () => {
                            const processor = new ZhuoLeProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.result
                    },
                    '向阳彩鸿湾': {
                        processor: XiangYangCaiHongWanProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYangCaiHongWanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '向阳康帝校区': {
                        processor: XiangYangKangDiProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYangKangDiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '向阳雅园校区': {
                        processor: XiangYangYaYuanProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYangYaYuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '向阳33小镇校区': {
                        processor: XiangYang33XiaoZhenProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYang33XiaoZhenProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '向阳星河城校区': {
                        processor: XiangYangXingHeChengProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYangXingHeChengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '向阳振兴城校区': {
                        processor: XiangYangZhenXingChengProcessor,
                        getDataMethod: async () => {
                            const processor = new XiangYangZhenXingChengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '拓德网球俱乐部': {
                        processor: TuoDeProcessor,
                        getDataMethod: async () => {
                            const processor = new TuoDeProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '爱动金丰网球俱乐部': {
                        processor: AiDongJinFengProcessor,
                        getDataMethod: async () => {
                            const processor = new AiDongJinFengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.result
                    },
                    '卓乐网球': {
                        processor: ZhuoLeTennisProcessor,
                        getDataMethod: async () => {
                            const processor = new ZhuoLeTennisProcessor();
                            return await processor.getVenueSettings({
                                userId: 5710920,
                                projectUid: "1725630736098549713",
                                dateTime: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.successed && data.result && data.result.slots
                    },
                    '爱力网球': {
                        processor: AiLiProcessor,
                        getDataMethod: async () => {
                            const processor = new AiLiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.result
                    },
                    '东城体育公园': {
                        processor: DongChengProcessor,
                        getDataMethod: async () => {
                            const processor = new DongChengProcessor();
                            return await processor.getVenueSettings({
                                date: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '为傲网球（香树店）': {
                        processor: WeiAoXiangShuProcessor,
                        getDataMethod: async () => {
                            const processor = new WeiAoXiangShuProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '埗击网球': {
                        processor: BuJiProcessor,
                        getDataMethod: async () => {
                            const processor = new BuJiProcessor();
                            return await processor.getVenueSettings({
                                dateTime: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.result
                    },
                    '月击网球（城市之光校区）': {
                        processor: YueJiChengShiZhiGuangProcessor,
                        getDataMethod: async () => {
                            const processor = new YueJiChengShiZhiGuangProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => {
                            // 月击网球数据结构: {code: 0, data: {list: [], site_x: [], site_y: []}}
                            return data && data.data && 
                                   data.data.site_x && Array.isArray(data.data.site_x) &&
                                   data.data.list && Array.isArray(data.data.list);
                        }
                    },
                    '月击网球（丰泰校区）': {
                        processor: YueJiFengTaiProcessor,
                        getDataMethod: async () => {
                            const processor = new YueJiFengTaiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => {
                            // 月击网球数据结构: {code: 0, data: {list: [], site_x: [], site_y: []}}
                            return data && data.data && 
                                   data.data.site_x && Array.isArray(data.data.site_x) &&
                                   data.data.list && Array.isArray(data.data.list);
                        }
                    },
                    '月击网球（电商园校区）': {
                        processor: YueJiDianShangYuanProcessor,
                        getDataMethod: async () => {
                            const processor = new YueJiDianShangYuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => {
                            // 月击网球数据结构: {code: 0, data: {list: [], site_x: [], site_y: []}}
                            return data && data.data && 
                                   data.data.site_x && Array.isArray(data.data.site_x) &&
                                   data.data.list && Array.isArray(data.data.list);
                        }
                    },
                    '月击网球（虎门大道校区）': {
                        processor: YueJiHuMenDaDaoProcessor,
                        getDataMethod: async () => {
                            const processor = new YueJiHuMenDaDaoProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => {
                            // 月击网球数据结构: {code: 0, data: {list: [], site_x: [], site_y: []}}
                            return data && data.data && 
                                   data.data.site_x && Array.isArray(data.data.site_x) &&
                                   data.data.list && Array.isArray(data.data.list);
                        }
                    },
                    '晟旋网球(大壮国际店)': {
                        processor: ShengXuanDaZhuangProcessor,
                        getDataMethod: async () => {
                            const processor = new ShengXuanDaZhuangProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '花果山网球馆': {
                        processor: HuaGuoShanProcessor,
                        getDataMethod: async () => {
                            const processor = new HuaGuoShanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '209网球中心': {
                        processor: TwoZeroNineTennisProcessor,
                        getDataMethod: async () => {
                            const processor = new TwoZeroNineTennisProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '锦林山庄网球馆': {
                        processor: JinLinShanZhuangProcessor,
                        getDataMethod: async () => {
                            const processor = new JinLinShanZhuangProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '丰泰花园网球场': {
                        processor: FengTaiHuaYuanProcessor,
                        getDataMethod: async () => {
                            const processor = new FengTaiHuaYuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '拓普网球(南国花园)': {
                        processor: TuoPuNanGuoHuaYuanProcessor,
                        getDataMethod: async () => {
                            const processor = new TuoPuNanGuoHuaYuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '拓普网球(新港东)': {
                        processor: TuoPuXinGangDongProcessor,
                        getDataMethod: async () => {
                            const processor = new TuoPuXinGangDongProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '拓普网球(白云湖金铂天地)': {
                        processor: TuoPuBaiYunHuJinBoTianDiProcessor,
                        getDataMethod: async () => {
                            const processor = new TuoPuBaiYunHuJinBoTianDiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '全爱网球(荔湾店)': {
                        processor: QuanAiLiWanProcessor,
                        getDataMethod: async () => {
                            const processor = new QuanAiLiWanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data
                    },
                    'Mteam网球(嘉禾广丰)': {
                        processor: MteamJiaHeGuangFengProcessor,
                        getDataMethod: async () => {
                            const processor = new MteamJiaHeGuangFengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    'Mteam网球(黄埔)': {
                        processor: MteamHuangPuProcessor,
                        getDataMethod: async () => {
                            const processor = new MteamHuangPuProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '东莞市体育中心': {
                        processor: DongGuanTiYuZhongXinProcessor,
                        getDataMethod: async () => {
                            const processor = new DongGuanTiYuZhongXinProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '3.5+网球（福地）': {
                        processor: ThreePointFiveFuDiProcessor,
                        getDataMethod: async () => {
                            const processor = new ThreePointFiveFuDiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '松山湖太鲁阁公园': {
                        processor: SongShanHuTaiLuGeProcessor,
                        getDataMethod: async () => {
                            const processor = new SongShanHuTaiLuGeProcessor();
                            return await processor.getVenueSettings({
                                date: this.selectedDate
                            });
                        },
                        validateData: (data) => data.data.data.data
                    },
                    '源峰网球': {
                        processor: YuanFengProcessor,
                        getDataMethod: async () => {
                            const processor = new YuanFengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.result
                    },
                    '罗杰网球': {
                        processor: LuoJieProcessor,
                        getDataMethod: async () => {
                            const processor = new LuoJieProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '晟旋网球(执信店)': {
                        processor: ShengXuanZhiXingProcessor,
                        getDataMethod: async () => {
                            const processor = new ShengXuanZhiXingProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    'UPTennis三溪SKY店': {
                        processor: UPTennisSanXiSKYProcessor,
                        getDataMethod: async () => {
                            const processor = new UPTennisSanXiSKYProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data
                    },
                    '快客网球': {
                        processor: KuaiKeProcessor,
                        getDataMethod: async () => {
                            const processor = new KuaiKeProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(中国大酒店)': {
                        processor: JinManGuanProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(皇冠假日)': {
                        processor: JinManGuanHuangGuanProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuangGuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(海珠香格里拉)': {
                        processor: JinManGuanHaiZhuProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHaiZhuProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(华工北)': {
                        processor: JinManGuanHuaGongBeiProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuaGongBeiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(华工西)': {
                        processor: JinManGuanHuaGongXiProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuaGongXiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(畔江花园)': {
                        processor: JinManGuanPanJiangHuaYuanProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanPanJiangHuaYuanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(天河城喜来登)': {
                        processor: JinManGuanTianHeChengProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanTianHeChengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(华工大学城)': {
                        processor: JinManGuanHuaGongDaXueChengProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuaGongDaXueChengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(威斯汀)': {
                        processor: JinManGuanWeiSiTingProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanWeiSiTingProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(白云)': {
                        processor: JinManGuanBaiYunProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanBaiYunProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(珠江新城)': {
                        processor: JinManGuanZhuJiangXinChengProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanZhuJiangXinChengProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(琶洲保利世贸)': {
                        processor: JinManGuanPaZhouProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanPaZhouProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(华美麓湖)': {
                        processor: JinManGuanHuaMeiLuHuProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuaMeiLuHuProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(华美学校)': {
                        processor: JinManGuanHuaMeiXueXiaoProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanHuaMeiXueXiaoProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '金满贯(旗峰山)': {
                        processor: JinManGuanQiFengShanProcessor,
                        getDataMethod: async () => {
                            const processor = new JinManGuanQiFengShanProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '裕丰围江边网球场': {
                        processor: YuFengWeiJiangBianProcessor,
                        getDataMethod: async () => {
                            const processor = new YuFengWeiJiangBianProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '拓普网球(万胜围)': {
                        processor: TuoPuWanShengWeiProcessor,
                        getDataMethod: async () => {
                            const processor = new TuoPuWanShengWeiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '健潮网球': {
                        processor: JianChaoTennisProcessor,
                        getDataMethod: async () => {
                            const processor = new JianChaoTennisProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '青芸网球': {
                        processor: QingYunTennisProcessor,
                        getDataMethod: async () => {
                            const processor = new QingYunTennisProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '云堡罗伦斯网球': {
                        processor: YunBaoLuoLunSiProcessor,
                        getDataMethod: async () => {
                            const processor = new YunBaoLuoLunSiProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    },
                    '瀚为网球': {
                        processor: HanWeiTennisProcessor,
                        getDataMethod: async () => {
                            const processor = new HanWeiTennisProcessor();
                            return await processor.getVenueSettings({
                                reserveDate: this.selectedDate
                            });
                        },
                        validateData: (data) => data && data.data
                    }
                };
                
                // 临时存储所有球馆数据，用于统一排序和筛选
                const allVenuesData = [];
                
                // 收集球馆数据的方法（不立即更新界面）
                const collectVenueData = (venues, venueName) => {
                    if (venues && venues.length > 0) {
                        // 转换数据模型但不应用过滤条件
                        let processedVenues = this.processVenues(venues);
                        allVenuesData.push(...processedVenues);
                    }
                };
                
                // 统一处理和排序所有数据的方法
                const processAllVenues = () => {
                    // 按距离排序所有场地
                    allVenuesData.sort((a, b) => {
                        if (a.distance !== undefined && b.distance !== undefined) {
                            return a.distance - b.distance;
                        }
                        if (a.distance !== undefined) {
                            return -1;
                        }
                        if (b.distance !== undefined) {
                            return 1;
                        }
                        return a.name.localeCompare(b.name);
                    });
                    
                    // 应用过滤条件
                    let filteredVenues = this.applyFilters(allVenuesData);
                    
                    // 更新界面
                    this.allVenueList = [...allVenuesData];
                    
                    // 根据当前过滤器状态更新显示列表
                    if (this.activeVenueFilter === 'all') {
                        this.venueList = [...filteredVenues];
                    } else {
                        // 如果有特定场馆过滤，只显示匹配的场馆
                        const matchingVenues = filteredVenues.filter(venue => 
                            venue.name && venue.name.includes(this.activeVenueFilter)
                        );
                        this.venueList = [...matchingVenues];
                    }
                };
                
                // 使用循环处理所有选中的球馆
                for (const clubName of selectedClubs) {
                    const venueConfig = venueProcessorMap[clubName];
                    if (venueConfig) {
                        venuePromises.push(
                            (async () => {
                                try {
                                    const data = await venueConfig.getDataMethod();
                                    if (venueConfig.validateData(data)) {
                                        const processor = new venueConfig.processor();
                                        const venues = processor.process(data, this.selectedDate);
                                        
                                        collectVenueData(venues, clubName);
                                    }
                                } catch (error) {
                                    console.log(`${clubName}数据加载失败:`, error);
                                }
                            })()
                        );
                    }
                }
                
                // 保留原有的库卡网球逻辑作为备用（如果不在映射中）
                if (selectedClubs.includes('库卡网球') && !venueProcessorMap['库卡网球']) {
                    venuePromises.push(
                        (async () => {
                            try {
                                const zhuoLeProcessor = new ZhuoLeProcessor();
                                const zhuoLeData = await zhuoLeProcessor.getVenueSettings({
                                    userId: 5710920,
                                    projectUid: "1725630736098549713",
                                    dateTime: this.selectedDate
                                });
                                
                                if (zhuoLeData && zhuoLeData.successed && zhuoLeData.result && zhuoLeData.result.slots) {
                                    const processor = new ZhuoLeProcessor();
                                    const venues = processor.process(zhuoLeData, this.selectedDate);
                                    collectVenueData(venues, '库卡网球');
                                }
                            } catch (error) {
                                console.log('库卡网球数据加载失败:', error);
                            }
                        })()
                    );
                }
                

                

                

                
                // 添加其他重要球馆的Promise查询
                // 所有球馆数据将通过统一的距离排序逻辑处理
                

                

                
                

                

                
                
                
                                // 等待所有球馆数据加载完成
                await Promise.allSettled(venuePromises);
                
                // 统一处理所有数据：排序和筛选
                processAllVenues();
                
                this.hasMore = false;
                
                // 如果场地列表为空，显示提示信息
                if (this.venueList.length === 0 && this.selectedTimeSlots.length > 0) {
                    uni.showToast({
                        title: '当前无空闲的场',
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('加载场地数据失败:', error);
                uni.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
            }
            // 移除finally块中的loading设置，由performSearch方法控制
        },
        
        // 应用过滤条件
        applyFilters(venues) {
            let filteredVenues = venues;
            
            // 根据搜索关键词过滤
            if (this.searchKeyword) {
                filteredVenues = filteredVenues.filter(item => 
                    (item.name && item.name.includes(this.searchKeyword)) || 
                    (item.address && item.address.includes(this.searchKeyword))
                );
            }
            
            // 根据球场类型配置过滤场地数据
            if (this.selectedCourtType !== '不限') {
                filteredVenues = filteredVenues.filter(item => 
                    this.checkCourtType(item)
                );
            }
            
            // 根据标准场过滤
            if (this.showStandardCourtsOnly) {
                filteredVenues = filteredVenues.filter(item => 
                    this.isStandardCourt(item)
                );
            }
            
            return filteredVenues;
        },
        
        // 处理场地数据模型
        processVenues(filteredVenues) {
                
            // 转换数据模型
            let venues = filteredVenues.map(item => {
                // 创建新的场地对象
                const venue = new Venue(item);
                
                // 如果有选中的时间槽，则根据时间槽设置available属性
                if (this.selectedTimeSlots.length > 0) {
                    const allTimeSlotsFree = this.selectedTimeSlots.every(selectedSlot => {
                        const matchingSlot = venue.timeSlots.find(slot => {
                            // 比较时间范围是否匹配
                            if (!slot.time) return false; // 安全检查，防止slot.time为undefined
                            const slotStartTime = slot.beginDatetime || `${this.selectedDate} ${slot.time.split('-')[0]}:00`;
                            const slotEndTime = slot.endDatetime || `${this.selectedDate} ${slot.time.split('-')[1]}:00`;
                            
                            // 解析选中的时间槽
                            const [selectedStartHour, selectedStartMinute] = selectedSlot.split('-')[0].split(':');
                            const [selectedEndHour, selectedEndMinute] = selectedSlot.split('-')[1].split(':');
                            
                            // 将日期格式转换为iOS支持的格式
                            const formatDateForIOS = (dateStr) => {
                                if (!dateStr) return new Date();
                                
                                // 如果已经是ISO格式或支持的格式，直接使用
                                if (dateStr.includes('T') || dateStr.includes('/')) {
                                    return new Date(dateStr);
                                }
                                
                                // 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 "yyyy/MM/dd HH:mm:ss"
                                const formattedStr = dateStr.replace(/-/g, '/');
                                return new Date(formattedStr);
                            };
                            
                            const selectedStartTime = formatDateForIOS(`${this.selectedDate} ${selectedStartHour}:${selectedStartMinute}:00`).getTime();
                            const selectedEndTime = formatDateForIOS(`${this.selectedDate} ${selectedEndHour}:${selectedEndMinute}:00`).getTime();
                            
                            const slotStart = formatDateForIOS(slotStartTime).getTime();
                            const slotEnd = formatDateForIOS(slotEndTime).getTime();
                            
                            // 检查时间范围是否有重叠
                            const isOverlap = selectedStartTime < slotEnd && selectedEndTime > slotStart;
                            
                            return isOverlap;
                        });
                        
                        // 如果找到匹配的时段且为空闲，则返回true
                        return matchingSlot && matchingSlot.isFree;
                    });
                    
                    venue.available = allTimeSlotsFree;
                } else {
                    // 如果没有选中的时间槽，将available设置为undefined
                    venue.available = undefined;
                }
                
                return venue;
            });
            
            return venues.filter(venue => venue.available !== false);
        },
        
        // 排序场地列表
        sortVenueList() {
            this.venueList.sort((a, b) => {
                // 如果distance属性存在，则按distance排序
                if (a.distance !== undefined && b.distance !== undefined) {
                    return a.distance - b.distance;
                }
                // 如果只有a有distance属性，则a排在前面
                if (a.distance !== undefined) {
                    return -1;
                }
                // 如果只有b有distance属性，则b排在前面
                if (b.distance !== undefined) {
                    return 1;
                }
                // 如果都没有distance属性，则按名称排序
                return a.name.localeCompare(b.name);
            });
            
            // 同时更新allVenueList的排序
            this.allVenueList.sort((a, b) => {
                if (a.distance !== undefined && b.distance !== undefined) {
                    return a.distance - b.distance;
                }
                if (a.distance !== undefined) {
                    return -1;
                }
                if (b.distance !== undefined) {
                    return 1;
                }
                return a.name.localeCompare(b.name);
            });
        },
        
        updateVenues(newVenues) {
            // 更新场馆列表数据
            // 注意：这里只更新显示数据，不更新allVenueList，避免影响球馆导航列表
            this.venueList = newVenues; // 显示数据
        },
        
        filterByVenue(venueFilter) {
            // 设置激活的过滤器
            this.activeVenueFilter = venueFilter;
            
            if (venueFilter === 'all') {
                // 显示所有场地
                this.venueList = [...this.allVenueList];
                // 清除标记点选中状态
                this.selectedMarkerId = null;
            } else {
                // 过滤出指定球馆的场地
                this.venueList = this.allVenueList.filter(venue => venue.dataSource === venueFilter);
                
                // 自动选中对应的地图标记点
                const targetMarker = this.mapMarkers.find(marker => marker.venueName === venueFilter);
                if (targetMarker) {
                    this.selectedMarkerId = targetMarker.id;
                }
            }
            
            // 重新生成地图标记点以更新选中状态
            this.generateMapMarkers();
            this.forceRefreshMapMarkers();
            
            // 如果当前是展开状态，选择球馆后自动收缩
            if (this.isVenueListExpanded) {
                this.isVenueListExpanded = false;
            }
        },
        
        filterByVenueAndAddress(venueFilter, addressInfo) {
            // 设置激活的过滤器
            this.activeVenueFilter = venueFilter;
            
            // 先过滤出指定球馆的场地
            let filteredVenues = this.allVenueList.filter(venue => venue.dataSource === venueFilter);
            
            // 如果地址信息中有include字段，进一步过滤场地
            if (addressInfo && addressInfo.include && Array.isArray(addressInfo.include)) {
                filteredVenues = filteredVenues.filter(venue => {
                    // 检查场地名称是否包含在该地址的include列表中
                    return addressInfo.include.some(includeName => 
                        venue.name.includes(includeName)
                    );
                });
            }
            
            this.venueList = filteredVenues;
            
            // 如果当前是展开状态，选择球馆后自动收缩
            if (this.isVenueListExpanded) {
                this.isVenueListExpanded = false;
            }
        },
        
        goToVenueDetail(venue) {
            // 跳转到场地详情页
            console.log('跳转到场地详情:', venue);
        },
        
        loadMoreVenues() {
            this.loadVenueData();
        },
        
        checkCourtType(venue) {
            // 如果选择的是"不限"，则返回true
            if (this.selectedCourtType === '不限') {
                return true;
            }
            
            // 获取当前球场类型的配置
            const typeConfig = this.courtTypeConfig[this.selectedCourtType];
            if (!typeConfig) {
                return true; // 如果没有该类型的配置，默认显示
            }
            
            // 获取当前球馆的配置
            const clubConfig = typeConfig[venue.dataSource];
            if (!clubConfig) {
                return false; // 如果该球馆没有配置此类型，则不显示
            }
            
            // 检查场地名称是否匹配配置
            const venueName = venue.name;
            
            // 如果配置是数组，则检查场地名称是否包含数组中的任意一个词
            if (Array.isArray(clubConfig)) {
                return clubConfig.some(configName => 
                    venueName.includes(configName)
                );
            }
            
            // 如果配置了exclude，则排除指定场地（优先级最高）
            if (clubConfig.exclude && clubConfig.exclude.length > 0) {
                return !clubConfig.exclude.some(excludeName => 
                    venueName.includes(excludeName)
                );
            }
            
            // 如果配置了include，则只包含指定场地
            if (clubConfig.include && clubConfig.include.length > 0) {
                return clubConfig.include.some(includeName => 
                    venueName.includes(includeName)
                );
            }
            
            // 如果配置了arrayMatch，则检查场地名称是否包含数组中的任意一个词
            if (clubConfig.arrayMatch && clubConfig.arrayMatch.length > 0) {
                return clubConfig.arrayMatch.some(matchWord => 
                    venueName.includes(matchWord)
                );
            }
            
            // 如果配置了includeAll，则包含所有场地
            if (clubConfig.includeAll) {
                return true;
            }
            
            // 默认不显示
            return false;
        },
        
        isStandardCourt(venue) {
            // 判断是否为标准场
            // 根据球场类型配置判断场地类型
            const venueName = venue.name;
            const dataSource = venue.dataSource;
            
            // 遍历球场类型配置
            for (const [courtType, venues] of Object.entries(this.courtTypeConfig)) {
                if (courtType === '不限') continue;
                
                const venueConfig = venues[dataSource];
                if (!venueConfig) continue;
                
                // 检查是否匹配
                if (Array.isArray(venueConfig)) {
                    if (venueConfig.some(configName => venueName.includes(configName))) {
                        return courtType !== '非标准场';
                    }
                } else if (venueConfig.include && venueConfig.include.length > 0) {
                    if (venueConfig.include.some(includeName => venueName.includes(includeName))) {
                        return courtType !== '非标准场';
                    }
                } else if (venueConfig.arrayMatch && venueConfig.arrayMatch.length > 0) {
                    if (venueConfig.arrayMatch.some(matchWord => venueName.includes(matchWord))) {
                        return courtType !== '非标准场';
                    }
                } else if (venueConfig.includeAll) {
                    return courtType !== '非标准场';
                }
            }
            
            // 默认为标准场
            return true;
        },
        
        // 地图相关方法
        initMapMarkers() {
            this.generateMapMarkers();
            this.getUserLocation();
        },
        
        // 重新初始化地图
        reinitializeMap() {
            // 清空当前标记点
            this.mapMarkers = [];
            this.selectedMarkerId = null;
            
            // 使用 nextTick 确保 DOM 更新后再重新生成标记点
            this.$nextTick(() => {
                this.generateMapMarkers();
            });
        },
        
        // 强制刷新地图标记点
        forceRefreshMapMarkers() {
            const currentMarkers = JSON.parse(JSON.stringify(this.mapMarkers));
            this.mapMarkers = [];
            
            this.$nextTick(() => {
                this.mapMarkers = currentMarkers;
            });
        },
        
        // 生成地图标记点
        generateMapMarkers() {
            const markers = [];
            
            let markerIndex = 0;
            
            // 只为 uniqueVenues 中的球馆生成标记点
            this.uniqueVenues.forEach(venueName => {
                // 先在大球场中查找
                const largeVenue = venueConfig.venues.find(venue => venue.name === venueName);
                if (largeVenue) {
                    largeVenue.addresses.forEach((address, addressIndex) => {
                        const latitude = Number(address.latitude);
                        const longitude = Number(address.longitude);
                        
                        if (!isNaN(latitude) && !isNaN(longitude)) {
                            let displayName = largeVenue.name.replace(/网球|俱乐部|校区|公园|中心|店/g, '');
                            
                            // 如果有多个地址，在显示名称中添加地址区分
                            if (largeVenue.addresses.length > 1) {
                                const districtName = address.district.replace(/街道|镇|区/g, '');
                                displayName = `${displayName}(${districtName})`;
                            }
                            
                            const currentMarkerId = markerIndex++;
                            
                            // 根据是否为选中状态设置样式
                            const isSelected = this.selectedMarkerId === currentMarkerId;
                            const bgColor = isSelected ? '#007AFF' : '#ffffff';
                            const textColor = isSelected ? '#ffffff' : '#000000';
                            
                            markers.push({
                                id: currentMarkerId,
                                latitude: latitude,
                                longitude: longitude,
                                title: largeVenue.name,
                                iconPath: '/static/court/court.png',
                                label: {
                                    content: displayName,
                                    color: textColor,
                                    fontSize: 12,
                                    bgColor: bgColor,
                                    borderRadius: 15,
                                    padding: 8,
                                    textAlign: 'center'
                                },
                                width: 0.1,
                                height: 0.1,
                                anchor: {
                                    x: 0.5,
                                    y: -1.0
                                },
                                venueType: 'large',
                                venueName: venueName,
                                addressIndex: addressIndex,
                                addressInfo: address,
                                originalBgColor: '#ffffff'
                            });
                        }
                    });
                }
            });
            
            this.mapMarkers = markers;
        },
        
        // 获取用户位置
        getUserLocation() {
            uni.getLocation({
                type: 'gcj02',
                success: (res) => {
                    this.mapLatitude = res.latitude;
                    this.mapLongitude = res.longitude;
                },
                fail: () => {
                    console.log('获取用户位置失败，使用默认位置');
                }
            });
        },
        
        // 计算两点间距离（单位：公里）
        calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371; // 地球半径（公里）
            const dLat = this.toRadians(lat2 - lat1);
            const dLon = this.toRadians(lon2 - lon1);
            const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                      Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
                      Math.sin(dLon / 2) * Math.sin(dLon / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return R * c;
        },
        
        // 角度转弧度
        toRadians(degrees) {
            return degrees * (Math.PI / 180);
        },
        
        // 按距离排序球馆
        sortVenuesByDistance(venues) {
            const userLat = this.mapLatitude;
            const userLon = this.mapLongitude;
            
            return venues.map(venue => {
                // 从venueConfig中获取球馆的经纬度信息
                const venueInfo = venueConfig.venues.find(v => v.name === venue || v.dataSource === venue);
                if (venueInfo && venueInfo.addresses && venueInfo.addresses.length > 0) {
                    // 使用主要地址的经纬度
                    const primaryAddress = venueInfo.addresses.find(addr => addr.isPrimary) || venueInfo.addresses[0];
                    const distance = this.calculateDistance(
                        userLat, userLon,
                        primaryAddress.latitude, primaryAddress.longitude
                    );
                    return { name: venue, distance: distance };
                }
                return { name: venue, distance: Infinity };
            }).sort((a, b) => a.distance - b.distance);
        },
        
        // 地图标记点点击事件
        onMarkerTap(e) {
            const markerId = e.markerId;
            const marker = this.mapMarkers.find(m => m.id === markerId);
            console.log(marker, markerId, e);
            
            if (marker) {
                // 更新选中的标记点ID
                this.selectedMarkerId = markerId;
                this.generateMapMarkers();
                this.forceRefreshMapMarkers();
                
                // 根据是否有地址信息来过滤场地
                if (marker.addressInfo) {
                    // 有地址信息，按地址过滤
                    this.filterByVenueAndAddress(marker.venueName, marker.addressInfo);
                } else {
                    // 没有地址信息，按球馆过滤
                    this.filterByVenue(marker.venueName);
                }
            }
        },

        // 初始化基于城市的球馆筛选
        initializeCityBasedFilter() {
            try {
                // 获取当前城市信息
                this.currentCity = getCurrentCity();
                console.log('当前城市:', this.currentCity);
                
                if (this.currentCity && this.currentCity.name === '广州市') {
                    // 如果当前城市是广州市，默认只显示广州市的球馆
                    this.setGuangzhouClubsFilter();
                    console.log('检测到广州市，已设置广州市球馆筛选');
                } else if (this.currentCity && this.currentCity.name === '东莞市') {
                    // 如果当前城市是东莞市，默认只显示东莞市的球馆
                    this.setDongguanClubsFilter();
                    console.log('检测到东莞市，已设置东莞市球馆筛选');
                }
            } catch (error) {
                console.error('初始化城市筛选失败:', error);
            }
        },

        // 根据城市设置球馆筛选
        setCityClubsFilter(cityName) {
            // 根据venueConfig.json中的城市信息获取球馆列表
            const cityVenues = venueConfig.venues.filter(venue => {
                return venue.addresses && venue.addresses.some(address => 
                    address.city === cityName
                );
            }).map(venue => venue.name);
            
            // 只选择当前城市的球馆，并且这些球馆在clubOptions中存在
            const cityClubs = this.clubOptions.filter(club => 
                club !== '所有球馆' && cityVenues.includes(club)
            );
            
            // 找到这些球馆在clubOptions中的索引
            const cityIndices = [];
            cityClubs.forEach(clubName => {
                const index = this.clubOptions.indexOf(clubName);
                if (index !== -1) {
                    cityIndices.push(index);
                }
            });
            
            if (cityIndices.length > 0) {
                // 设置选中的球馆为当前城市的球馆
                this.selectedClubs = cityIndices;
                this.selectedClubNames = cityClubs;
                console.log(`已设置${cityName}球馆筛选:`, cityClubs);
            }
        },

        // 设置广州市球馆筛选
        setGuangzhouClubsFilter() {
            this.setCityClubsFilter('广州市');
        },

        // 设置东莞市球馆筛选
        setDongguanClubsFilter() {
            this.setCityClubsFilter('东莞市');
        },

    },
    
    watch: {
        allVenueList: {
            handler() {
                // 当所有场地列表更新时，更新球馆列表
                this.updateUniqueVenues();
            },
            deep: true
        },
        venueList: {
            handler() {
                // 只有在没有激活过滤器时才更新球馆列表排序
                // 避免过滤操作导致uniqueVenues重新排序
                if (this.activeVenueFilter === 'all' || !this.activeVenueFilter) {
                    this.updateUniqueVenues();
                }
            },
            deep: true
        },
        uniqueVenues: {
            handler() {
                // 当球馆列表更新时，重新生成地图标记点
                this.generateMapMarkers();
            },
            deep: true
        }
    },
    
    async mounted() {
        // 初始化星期选择数据
        this.weekDays = this.generateWeekDays();
        
        // 初始化地图
        this.initMapMarkers();
        
        // 检测当前城市并设置默认球馆筛选
        this.initializeCityBasedFilter();
        
        // 等待一个微任务，确保城市筛选设置完成
        await this.$nextTick();
        
        // 设置loading状态并自动加载场地数据
        this.loading = true;
        this.loadVenueData().finally(() => {
            this.loading = false;
        });
        
        // 监听来自首页的搜索模态框打开事件
        uni.$on('openSearchModal', () => {
            this.openSearchModal();
        });
    },
    
    beforeDestroy() {
        // 移除事件监听
        uni.$off('openSearchModal');
    }
}
</script>

<style lang="scss">
@font-face {
  font-family: 'AaHouDiHei';
  src: url('https://mp-0c81a8be-aa9a-4fae-8d6c-54b797768401.cdn.bspapp.com/cloudstorage/SmileySans-Oblique-3.otf') format('truetype');
  font-weight: normal;
  font-style: normal;
}
.container {
    position: relative;
    // min-height: 100vh;
}

// 导航栏样式
.custom-nav-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    height: 88rpx;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 999;
    padding-top: env(safe-area-inset-top);
    
    &.nav-transparent {
        background-color: transparent;
    }
}

.nav-left, .nav-right {
    // width: 80rpx;
    display: flex;
    align-items: center;
}

.nav-center {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    margin-right: 30rpx;
}

.back-button:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 1);
}

.back-icon {
    width: 36rpx;
    height: 36rpx;
    transform: rotate(180deg);
}

.nav-bar-image {
    &.logo-image {
        width: 270rpx;
        height: 68rpx;
    }

    &.bg-image {
        width: 750rpx;
        height: 528rpx;
    }

    &.main-image {
        width: 686rpx;
        height: 382rpx;
        margin: 20rpx;
    }

    &.sub-image-left {
        width: 332rpx;
        height: 164rpx;
        margin-right: 13rpx;
    }

    &.sub-image-right {
        width: 332rpx;
        height: 164rpx;
        margin-left: 13rpx;
    }
}

.bg-image-container {
    position: absolute;
    z-index: 0;
    top: -200rpx;
}

.scroll-view-container {
    width: 720rpx;
    overflow-x: scroll;
    padding-left: 30rpx;
    display: flex;
    margin-top: 30rpx;
    margin-bottom: 40rpx;

    .court-type {
        margin-right: 44rpx;
        font-size: 32rpx;
        color: #999;
        width: max-content;
        max-width: 200rpx;
        font-weight: bold;
        position: relative;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .court-type:last-child{
        margin-right: 150rpx;
    }

    .court-type.active {
        color: #333;
    }

    .loading-venue {
        display: flex;
        align-items: center;
        gap: 8rpx;
        color: #999;
        
        .loading-icon-small {
            width: 24rpx;
            height: 24rpx;
            animation: rotate 1s linear infinite;
            filter: brightness(0) saturate(100%) invert(60%) sepia(0%) saturate(0%) hue-rotate(0deg) brightness(60%) contrast(100%);
        }
        
        text {
            font-size: 28rpx;
        }
    }

    .active::after{
        content: "";
        position: absolute;
        bottom: 0;
        left: 0;
        width: -webkit-fill-available;
        height: 21rpx;
        background-color: #42CF7F8F;
        border-radius: 3rpx;
        z-index: -1;
    }
}

// 模态框样式
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 998;
}



.search-modal {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: white;
    border-top-left-radius: 30rpx;
    border-top-right-radius: 30rpx;
    z-index: 999;
    transform: translateY(100%);
    transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    max-height: 80vh;
}

.search-modal.modal-show {
    transform: translateY(0);
}

.modal-header {
    padding: 40rpx 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.filter-toggle {
    display: flex;
    align-items: center;
    gap: 10rpx;
}

.filter-label {
    font-size: 24rpx;
    color: #666;
    white-space: nowrap;
}

.modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.modal-cancel {
    font-size: 28rpx;
    color: #999;
    padding: 30rpx;
    margin: -30rpx;
}

.search-input-container {
    display: flex;
    align-items: center;
    background-color: #f7f7f7;
    border-radius: 24rpx;
    padding: 0 20rpx;
    height: 80rpx;
}

.search-input {
    flex: 1;
    height: 100%;
    font-size: 26rpx;
    color: #333;
    background-color: transparent;
}

.clear-btn {
    font-size: 40rpx;
    color: #999;
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.search-filters {
    padding: 30rpx 20rpx 30rpx;
}

.filter-item {
    padding: 10rpx 0;
}

.filter-item:last-child {
    border-bottom: none;
}

.filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
}

.filter-value {
    font-size: 28rpx;
    color: #999;
    display: flex;
    align-items: center;
}

.arrow {
    margin-left: 10rpx;
    font-size: 24rpx;
}

.modal-actions {
    display: flex;
    padding: 30rpx;
    gap: 20rpx;
    margin-bottom: env(safe-area-inset-bottom);
}

.reset-btn {
    flex: 0.5;
    height: 100rpx;
    background-color: #f7f7f7;
    color: #666;
    border-radius: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
}

.search-btn {
    flex: 1;
    height: 100rpx;
    background-color: #42CF7F;
    color: white;
    border-radius: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease;
}

.search-btn.loading {
    background-color: #95E5B8;
    cursor: not-allowed;
}

.loading-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 10rpx;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

// 时间标签样式
.time-tags-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    min-height: 40rpx;
    flex: 1;
    overflow: hidden;
}

.time-selected-tag {
    display: inline-flex;
    align-items: center;
    background: rgba(66, 207, 127, .1);
    border: 1rpx solid rgba(66, 207, 127, 1);
    border-radius: 20rpx;
    padding: 8rpx 16rpx;
    margin: 4rpx 8rpx 4rpx 0;
    font-size: 24rpx;
    color: rgb(54, 167, 103);
    max-width: 180rpx;
    min-width: 0;
}

.time-tag-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
    min-width: 0;
}

.time-tag-remove {
    margin-left: 8rpx;
    font-size: 28rpx;
    color: rgba(66, 207, 127, 1);
    cursor: pointer;
    font-weight: bold;
    line-height: 1;
}

// 底部弹窗样式
.bottom-modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: flex;
    align-items: flex-end;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease;
}

.bottom-modal-mask.show {
    opacity: 1;
    visibility: visible;
}

.bottom-modal {
    width: 100%;
    background-color: white;
    border-top-left-radius: 30rpx;
    border-top-right-radius: 30rpx;
    transform: translateY(100%);
    transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    max-height: 80vh;
}

.bottom-modal.show {
    transform: translateY(0);
}

.bottom-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.bottom-modal-content {
    padding: 40rpx;
    max-height: 600rpx;
    overflow-y: auto;
}

.bottom-modal-footer {
    padding: 30rpx 40rpx 100rpx;
    border-top: 1rpx solid #eee;
}

.modal-buttons {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
}

.modal-reset-button {
    flex: 0.5;
    height: 100rpx;
    background-color: #f7f7f7;
    color: #666;
    border-radius: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
}

.confirm-button {
    flex: 1;
    height: 100rpx;
    background-color: #42CF7F;
    color: white;
    border-radius: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
}

// 日期选择器样式
.date-picker-view {
    height: 400rpx;
    width: 100%;
}

.picker-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80rpx;
    font-size: 28rpx;
    color: #333;
}

// 时间选择网格样式
.time-tags-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    padding: 20rpx 0;
}

.time-tag-popup {
    padding: 20rpx;
    backdrop-filter: blur(10px);
    border-radius: 24rpx;
    font-size: 26rpx;
    text-align: center;
    color: #333;
    border: 1rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 2rpx 8rpx 0 rgba(31, 38, 135, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;
}

.time-tag-popup.active {
    background-color: #42CF7F;
    backdrop-filter: blur(10px);
    color: white;
    border-color: #42CF7F;
    box-shadow: 0 4rpx 16rpx 0 rgba(66, 207, 127, 0.3);
}

.time-tag-popup.golden-time {
     padding: 20rpx;
    backdrop-filter: blur(10px);
    border-radius: 24rpx;
    font-size: 26rpx;
    text-align: center;
    color: #333;
    border: 1rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 2rpx 8rpx 0 rgba(31, 38, 135, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;
}

.time-tag-popup.golden-time.active {
    background-color: #42CF7F;
    backdrop-filter: blur(10px);
    color: white;
    border-color: #42CF7F;
    box-shadow: 0 4rpx 16rpx 0 rgba(66, 207, 127, 0.3);
}

.time-tag-popup.disabled {
    background-color: rgba(200, 200, 200, 0.5);
    color: #999;
    cursor: not-allowed;
    opacity: 0.5;
}

.time-label-popup {
    font-size: 26rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

// 内容区域样式
.content {
}

/* 自定义开关样式 - iOS 液态玻璃效果 */
.custom-switch {
  position: relative;
  width: 105rpx;
  height: 44rpx;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 202rpx;
  border: 1px solid rgba(255, 255, 255, 0.5);
  box-shadow: 
    0 4rpx 12rpx 0 rgba(0, 0, 0, 0.1),
    inset 0 1rpx 2rpx 0 rgba(255, 255, 255, 0.8);
  transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  cursor: pointer;
}

.custom-switch.active {
  background: rgba(66, 207, 127, 1);
  border-color: rgba(66, 207, 127, 0.6);
  box-shadow: 
    0 4rpx 16rpx 0 rgba(66, 207, 127, 0.4),
    inset 0 1rpx 2rpx 0 rgba(255, 255, 255, 0.6);
}

.switch-thumb {
  position: absolute;
  top: 3rpx;
  left: 3rpx;
  width: 62rpx;
  height: 38rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 109rpx;
  box-shadow: 
    0 2rpx 8rpx 0 rgba(0, 0, 0, 0.15),
    inset 0 1rpx 2rpx 0 rgba(255, 255, 255, 0.9);
  transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
}

.custom-switch.active .switch-thumb {
  transform: translateX(36rpx);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 
    0 2rpx 10rpx 0 rgba(66, 207, 127, 0.3),
    inset 0 1rpx 2rpx 0 rgba(255, 255, 255, 0.95);
}

/* 开关点击反馈效果 */
.custom-switch:active {
  transform: scale(0.95);
}

.custom-switch.active:active {
  transform: scale(0.95);
}
.all-icon{
    width: 74rpx;
    height: 47rpx;
    position: absolute;
    right: 0;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 0 10rpx;
    z-index: 1;
    image{
        transform: rotate(90deg);
        transition: transform 0.3s ease;
    }
}

.expand-arrow {
    width: 36rpx;
    height: 36rpx;
    transform: rotate(90deg);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.expand-arrow.expanded {
    transform: rotate(270deg);
}

// 展开状态的球馆列表样式
.expanded-venue-container {
    // padding: 30rpx;
    background-color: #fff;
    
    max-height: 0;
    overflow: hidden;
    opacity: 0;
    transform: translateY(-20rpx);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.expanded-venue-container.show {
    max-height: 2000rpx;
    padding-top: 30rpx;
    margin-bottom: 40rpx;
    opacity: 1;
    transform: translateY(0);
}

.expanded-venue-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding:  0 0 0 30rpx;
    
    .expanded-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
    }
    
    .all-icon {
        position: relative;
        right: auto;
        
        image {
            transform: rotate(90deg);
        }
    }
}

.expanded-venue-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    padding: 20rpx;
}

.expanded-court-type {
    padding: 20rpx;
    text-align: center;
    font-size: 28rpx;
    color: #999;
    background-color: #f7f7f7;
    border-radius: 24rpx;
    font-weight: bold;
    transition: all 0.3s ease;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0;
}

.expanded-court-type.active {
    color: #42CF7F;
    background-color: rgba(66, 207, 127, 0.1);
    border: 1rpx solid #42CF7F;
}

.expanded-court-type:hover {
    background-color: #e8e8e8;
}

.expanded-court-type.active:hover {
    background-color: rgba(66, 207, 127, 0.15);
}

/* 地图样式 */
.map-section {
    padding: 0 20rpx;
    margin-bottom: 20rpx;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-map-container {
    width: 100%;
    border-radius: 24rpx;
    overflow: hidden;
    transition: height 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 地图收缩状态 */
.search-map-container.map-collapsed {
    height: 0rpx;
    display: none;
}

/* 地图展开状态 */
.search-map-container.map-expanded {
    height: 800rpx;
}

.marker-transition {
    transition: all 0.3s ease;
}

/* 地图切换按钮样式 */
.map-toggle-container {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.map-toggle-container:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 0.8);
}

.map-toggle-icon {
    width: 80rpx;
    height: 80rpx;
    transition: all 0.3s ease;
}

// 搜索头部样式
.search-header {
    display: flex;
    align-items: flex-end;
}

.search-container {
    flex: 1;
    margin: 0 auto;
    margin-top: 200rpx;
    margin-right: 20rpx;
    margin-left: 20rpx;
}

.search-input-box {
    font-size: 26rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: auto;
    height: 80rpx;
    background: #F7F7F7;
    border-radius: 24rpx;
    max-width: 497rpx;
}

.search-input-content {
    display: flex;
    align-items: center;
    flex: 1;
    overflow: hidden;
    min-width: 0;
}

.search-icon {
    width: 36rpx;
    height: 36rpx;
    margin: 0 30rpx;
}

.search-text-container {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
    max-width: calc(100% - 100rpx);
}

.search-selected-text {
    color: #333;
    font-size: 28rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

.search-time-slots {
    margin-left: 10rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-placeholder {
    color: #999;
    font-size: 26rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-button {
    width: 144rpx;
    height: 80rpx;
    background-color: #42CF7F;
    margin-top: 100px;
    // margin-right: 20rpx;
    text-align: center;
    line-height: 80rpx;
    border-radius: 24rpx;
    color: #fff;
    padding: 0 30rpx;
    transition: all 0.3s ease;
    box-sizing: border-box;
}

.search-button.loading {
    background-color: #95E5B8;
    cursor: not-allowed;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 5rpx !important;
    font-size: 24rpx !important;
}

/* 星期选择样式 */
.week-selector-container {
    width: 690rpx;
    margin: 0rpx auto;
    margin-bottom: 20rpx;
}

.week-scroll-view {
    width: 100%;
    white-space: nowrap;
}

.week-days-container {
    display: flex;
    flex-direction: row;
    gap: 12rpx;
    // padding: 0 20rpx;
    width: fit-content;
    font-family: 'AaHouDiHei';
}

.week-day-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-width: 80rpx;
    height: 100rpx;
    background: #F7F7F7;
    border-radius: 16rpx;
    padding: 8rpx 12rpx;
    transition: all 0.3s ease;
    cursor: pointer;
}

.week-day-item.active {
    background: #42CF7F;
    color: white;
    .week-day-date {
    font-size: 26rpx;
    color: #fff !important;
}
}

.week-day-item.today {
    border: 2rpx solid #42CF7F;
}

.week-day-item.today.active {
    border: 2rpx solid #42CF7F;
    background: #42CF7F;
}


.week-day-name {
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 4rpx;
    color: inherit;
}

.week-day-date {
    font-size: 26rpx;
    color: #666;
}

/* 旋转动画 */
@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>